package io.jft.doll.ui.feedback

import android.annotation.SuppressLint
import android.content.DialogInterface
import android.content.Intent
import android.databinding.ObservableField
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.view.View
import android.widget.ImageView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.g.base.databind.setBackgroundImage
import com.g.base.extend.mainIoSchedulers
import com.g.base.extend.progressSubscribe
import com.g.base.extend.toast
import com.g.base.help.TakePhotoHelp
import com.g.base.router.RouteExtras
import com.g.base.ui.BaseActivity
import com.jph.takephoto.app.TakePhoto
import com.jph.takephoto.model.TResult
import io.jft.doll.R
import io.jft.doll.api.UserApi
import io.jft.doll.api.apiProviderMock
import io.jft.doll.databinding.ActivityFeedbackBinding
import io.jft.doll.router.RouterPage
import io.jft.doll.ui.imagePreview.OnPhotoRemoveEvent
import okhttp3.MediaType
import okhttp3.RequestBody
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.util.HashMap
import kotlin.collections.ArrayList

/**
 * Created by G on 2017/12/16 0016.
 */
@Route(path = RouterPage.FeedBackActivity, extras = RouteExtras.NeedOauth)
class FeedbackActivity : BaseActivity<ActivityFeedbackBinding>(), TakePhoto.TakeResultListener {
    override var hasToolbar: Boolean = true
    val inputDetail = ObservableField<String>()
    private val maxSelect = ObservableField(6)
    private var checkedPhoto = ArrayList<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_feedback)

        toolbar.title = "建议反馈"
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_toolbar_24dp)
        toolbar.setNavigationOnClickListener { finishAfterTransition() }
        toolbar.inflateMenu(R.menu.commit)
        toolbar.setOnMenuItemClickListener { commitFeedback(); return@setOnMenuItemClickListener true }

        val takePhotoInstant = TakePhotoHelp.getInstant(this, this, maxSelect)
        contentView.imagesLayout!!.addImage.setOnClickListener {
            maxSelect.set(maxOf(0, 6 - checkedPhoto.size))
            takePhotoInstant.startPhotoChoice()
        }
        contentView.data = this
        setupPhotoPicker()
        showContentView()
    }

    @SuppressLint("CheckResult")
    private fun commitFeedback() {
        if (inputDetail.get().isNullOrBlank() || inputDetail.get()!!.length <= 5) {
            toast("建议反馈的内容最少5个字符")
        } else {
            //创建参数
            val paramsMap: HashMap<String, RequestBody> = HashMap()
            paramsMap["feedbackDetail"] = convertToRequestBody(inputDetail.get()!!)
            checkedPhoto.forEachIndexed { index, it ->
                val convertToRequestBody = convertToRequestBody(File(it))
                paramsMap["file$index\"; filename=\"$it"] = convertToRequestBody
            }
            apiProviderMock.create(UserApi::class.java)
                    .postFeedback(paramsMap)
                    .mainIoSchedulers()
                    .progressSubscribe(
                            showSucceed = {
                                it.dismiss()
                                finishAfterTransition()
                            },
                            showError = {
                                it.dismiss(true)
                            }
                    )
        }
    }

    override fun takeSuccess(result: TResult?) {
        if (result == null) {
            toast("选择图片为空")
        } else {
            checkedPhoto.addAll(result.images.map { it.compressPath })
            setupPhotoPicker()
        }
    }

    override fun takeCancel() {
        toast("你没有选择图片")
    }

    override fun takeFail(result: TResult?, msg: String?) {
        AlertDialog.Builder(this)
                .setTitle("允许拍照")
                .setCancelable(true)
                .setMessage(msg ?: "没有拍照的权限")
                .setPositiveButton("去设置") { dialogInterface: DialogInterface, i: Int ->
                    val localIntent = Intent()
                    localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    localIntent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                    localIntent.data = Uri.fromParts("package", this.packageName, null)
                    startActivity(localIntent)
                }
                .setNegativeButton("算了,我不传图片了") { dialogInterface: DialogInterface, i: Int -> }
                .show()
    }


    private fun setupPhotoPicker() {
        contentView.imagesLayout!!.addImage.visibility = if (checkedPhoto.size >= 6) View.GONE else View.VISIBLE
        for (i in 0 until contentView.imagesLayout!!.rootLayout.childCount) {
            val imageView = contentView.imagesLayout!!.rootLayout.getChildAt(i) as? ImageView
                    ?: continue
            val uri = checkedPhoto.getOrNull(i)
            if (uri != null) {
                imageView.visibility = View.VISIBLE
                imageView.setOnClickListener { ARouter.getInstance().build(RouterPage.ImagePreview).withString("image", uri).withBoolean("needRemove", true).navigation(this) }
                setBackgroundImage(imageView, uri)
            } else {
                imageView.visibility = View.GONE
            }
        }
        contentView.imagesLayout!!.rootLayout.requestLayout()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onPhotoRemoveEvent(photoRemoveEvent: OnPhotoRemoveEvent) {
        checkedPhoto.remove(photoRemoveEvent.url)
        setupPhotoPicker()
    }

    private fun convertToRequestBody(param: String): RequestBody =
            RequestBody.create(MediaType.parse("text/plain"), param)


    private fun convertToRequestBody(param: File): RequestBody =
            RequestBody.create(MediaType.parse("image/jpeg"), param)

}